# -*- coding: utf-8 -*-
import cgi
import os
import logging

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from django.utils import simplejson as json

class MainPage(webapp.RequestHandler):
  def get(self):

    user = users.get_current_user()

    if user:
      url = users.create_logout_url(self.request.uri)
      url_linktext = '登出系統'
      is_login = True
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = '登入系統'
      is_login = False

    template_values = {
      'url': url,
      'url_linktext': url_linktext,
      'is_login':is_login
      }

    if user:
      #logging.info(user)
      template_values['nickname'] =  user.nickname()
      template_values['is_admin'] =  users.is_current_user_admin()
      template_values['email'] =  user.email()
      template_values['user_id'] =  user.user_id()

    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

class UserInfo(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    userinfo = {}
    if user:
      userinfo['is_login'] = True
      userinfo['nickname'] =  user.nickname()
      userinfo['is_admin'] =  users.is_current_user_admin()
      userinfo['email'] =  user.email()
      userinfo['user_id'] =  user.user_id()
    else:
      userinfo['is_login'] = False

    callback = self.request.get('callback')

    if callback :
      self.response.out.write(callback+'(')

    json.dump(userinfo, self.response.out)
    if callback :
      self.response.out.write(');')


application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/userinfo', UserInfo)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
